package com.kipling.kio.client;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

import com.alibaba.fastjson.JSON;
import com.kipling.kio.client.entity.ShowcasePacket;


public class TalkClient {


    /**
     * 创建客户端
     *
     * @param hostName
     * @param port
     * @throws IOException
     */
    public static void buildClient(String hostName, int port, String self, String friend) throws IOException {

        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress(hostName, port));

        Selector selector = Selector.open();

        socketChannel.configureBlocking(false);
        //接收朋友发来的信息
        socketChannel.register(selector, SelectionKey.OP_READ);
        Scanner scanner = new Scanner(System.in);
        ClientReadThread clientReadThread = new ClientReadThread(selector);
        Thread thread = new Thread(clientReadThread);
        thread.start();
      
        ShowcasePacket requestEntity = new ShowcasePacket();
        requestEntity.setType(3);
        requestEntity.setUserid(self);
        Map<String,Object> data = new HashMap<String,Object>();
        data.put("gameid", "1001");
        data.put("msg", "test");
        data.put("channel", "1043");
        data.put("userid", self);
        
        requestEntity.setContent(JSON.toJSONString(data));
        socketChannel.write(ByteBuffer.wrap(JSON.toJSONString(requestEntity).getBytes(ShowcasePacket.CHARSET)));
        while (scanner.hasNextLine()) {
            String send = scanner.nextLine();
            ShowcasePacket packet = new ShowcasePacket();
            packet.setType(1);
            packet.setUserid(self);
            Map<String,Object> data1 = new HashMap<String,Object>();
            data1.put("gameid", "10001");
            data1.put("channel", "1043");
            data1.put("text", send);
            data1.put("toUserid", friend);
            packet.setContent(JSON.toJSONString(data1));            
            socketChannel.write(ByteBuffer.wrap(JSON.toJSONString(packet).getBytes(ShowcasePacket.CHARSET)));
        }
    }
}
